/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.ipti.br.tag.bo;

import org.ipti.br.tag.dao.LoginFacade;
import org.ipti.br.tag.entity.Login;
import org.ipti.br.tag.entity.Person;
import java.io.Serializable;
import java.util.Calendar;
import java.util.List;
import javax.inject.Inject;
import javax.ejb.Stateless;
import org.ipti.br.tag.util.CalendarUtil;
import org.ipti.br.tag.util.EncryptionUtil;
import org.ipti.br.tag.util.LoginUtil;

/**
 *
 * @author root
 */
@Stateless
public class LoginBO implements Serializable {

    @Inject
    private LoginFacade loginDAO;
    @Inject
    private ConfigurationsBO configurationsBO;

    public LoginFacade getLoginDAO() {
        return loginDAO;
    }
    
    public void create(Login login) {
        if (login.getUserName() == null || login.getUserName().isEmpty() || "".equals(login.getUserName())) {
            login.setUserName(configurationsBO.getSerialNumber().toString()+login.getPerson().getId());
        }
        getLoginDAO().create(login);
    }

    public void create(String userName, Person person) {
        Login login = new Login();
        
        login.setPerson(person);
        login.setUserName(LoginUtil.selectNumbersLetters(userName));
        if (login.getUserName().isEmpty()) {
            login.setUserName(configurationsBO.getSerialNumber().toString()+login.getPerson().getId());
        }
        login.setPassword(EncryptionUtil.encrypt(LoginUtil.passwordGenerator(CalendarUtil.getFormatedDate(person.getBirthday()))));
        
        getLoginDAO().create(login);
    }

    public void edit(Login login) {
        getLoginDAO().edit(login);
    }

    public void remove(Login login) {
        getLoginDAO().remove(login);
    }

    public Login find(Object id) {
        return getLoginDAO().find(id);
    }

    public List<Login> findAll() {
        return getLoginDAO().findAll();
    }

    public Long validateLogin(Login login) {
        Login loginAux = getLoginDAO().findLoginPerUserName(login.getUserName());
        if (loginAux != null && EncryptionUtil.auth(login.getPassword(), loginAux.getPassword())) {
            return loginAux.getPerson().getId();
        }
        return null;
    }
    
    public List<Login> searchLogins(String userName) {
        return getLoginDAO().searchLogins(userName);
    }

    public List<Login> modifiedLoginBetweenDate(Calendar initialDate, Calendar finalDate, Long serialNumber) {
        return getLoginDAO().modifiedLoginBetweenDate(initialDate, finalDate, serialNumber);
    }

    public Login findLoginPerPerson(Long personID) {
        return getLoginDAO().findLoginPerPerson(personID);
    }

    public List<Login> findAllOrder() {
        return getLoginDAO().findAllOrder();
    }
}
